//备注：拷贝代码请加上作者信息
//作者：王海涛
//邮箱：1126471088@qq.com
//版本：V0.1.1
#include "bkp_bsp.h"
#include <string.h>

/*BKP的1到10共10个数据寄存器*/
#define BKP_DR1_10     10
/*BKP的10到42共32个数据寄存器*/
#define BKP_DR10_42    32


/*BKP备份寄存器的总缓存*/
static unsigned short WHT_BKP_BSP_Data[WHT_BKP_BSP_DATA_SIZE / 2] = { 0 };

/*BKP 启动*/
static void WHT_BKP_BSP_Start(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP|RCC_APB1Periph_PWR, ENABLE);//open BKP PWR clock
}
/*BKP复位*/
static void WHT_BKP_BSP_Reset(void)
{
	BKP_DeInit();
}
/*BKP读取到用户缓存里*/
static void WHT_BKP_BSP_Read(WHT_BKP_Cache_t* cache)
{
	unsigned short BKP_DR_Reg_Offset;

	if ((cache->Start_Addr + cache->TRx_Count) > cache->Buf_Size)
		return;
	
	BKP_DR_Reg_Offset = BKP_DR1;
	for (int i = 0; i < WHT_BKP_BSP_DATA_SIZE / 2; i++)
	{
		WHT_BKP_BSP_Data[i] = BKP_ReadBackupRegister(BKP_DR_Reg_Offset);
		if (i == (BKP_DR1_10 - 1))
			BKP_DR_Reg_Offset = BKP_DR11;
		else
			BKP_DR_Reg_Offset += BKP_DR1;
	}
	memcpy(cache->TRx_Buf, ((unsigned char*)WHT_BKP_BSP_Data) + cache->Start_Addr, cache->TRx_Count);
}
/*BKP写入用户缓存数据*/
static void WHT_BKP_BSP_Write(const WHT_BKP_Cache_t* cache)
{
	unsigned short BKP_DR_Reg_Offset;

	if ((cache->Start_Addr + cache->TRx_Count) > cache->Buf_Size)
		return;

	memcpy(((unsigned char*)WHT_BKP_BSP_Data) + cache->Start_Addr, cache->TRx_Buf, cache->TRx_Count);
	PWR_BackupAccessCmd(ENABLE);                                            //open RTC & BKP registers write mode
	BKP_DR_Reg_Offset = BKP_DR1;
	for (int i = 0; i < WHT_BKP_BSP_DATA_SIZE / 2; i++)
	{
		BKP_WriteBackupRegister(BKP_DR_Reg_Offset,WHT_BKP_BSP_Data[i]);
		if (i == (BKP_DR1_10 - 1))
			BKP_DR_Reg_Offset = BKP_DR11;
		else
			BKP_DR_Reg_Offset += BKP_DR1;
	}
	PWR_BackupAccessCmd(DISABLE);                                            //close RTC & BKP registers write mode
}


/*全局常量*/
const WHT_BKP_BSP_t WHT_BKP_BSP =
{
	.WHT_RW_Start = WHT_BKP_BSP_Start,
	.WHT_Reset    = WHT_BKP_BSP_Reset,
	.WHT_Read     = WHT_BKP_BSP_Read,
	.WHT_Write    = WHT_BKP_BSP_Write,
};
